package bbk.nfc.opt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import bbk.nfc.R;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.PowerManager;
import android.os.SystemClock;
import android.provider.AlarmClock;
import android.provider.Browser;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

public class OptApp
{
	public static final String TAG = "NFC_OptApp";
	public static final int PICK_CONTACT = 100001;
	public static final int PICK_APP = 100002;
	private static OptApp m_app = null;
	private Context mContext = null;
	private BroadcastReceiver mTimerServer = null;
	
	private OptApp(Context context)
	{
		mContext = context;
		mAM = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
		initWhiteList();
	}
	
	public static OptApp getOptApp(Context context)
	{
		if (m_app == null)
		{
			m_app = new OptApp(context);
		}
		return m_app;
	}
	
	public static void release()
	{
		if (m_app != null)
		{
			m_app.mContext = null;
			m_app = null;
		}
	}
	//alarm
	public void startAlarm(int hour, int min, String message)
	{
		if (hour < 0 || hour >= 24)
			return;
		if (min < 0 || min >= 60)
			return;
		Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
		i.putExtra(AlarmClock.EXTRA_HOUR, hour);
		i.putExtra(AlarmClock.EXTRA_MINUTES, min);
		i.putExtra(AlarmClock.EXTRA_MESSAGE, message);
		i.putExtra(AlarmClock.EXTRA_SKIP_UI, false);
		if (OptBBK.checkBBK())
		{
			mContext.sendBroadcast(i);
		}
		else
		{
			mContext.startActivity(i);
		}
	}
	
	//timer
	static final String NFC_TIMER_INTENT = "com.nfc.timer.intent";
	static final String ID = "id";
	static final String TIME = "alarm_time";
	static final String TIMER_DATA = "content://calendar/calendar_alerts/1";
	
	public void startTimer(long time)
	{
		registerReceiver();
		AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(NFC_TIMER_INTENT);
		//		intent.setClass(mContext, NfcTimerReceiver.class);
		//		intent.setData(Uri.parse(TIMER_DATA));
		intent.putExtra(ID, 1);
		long atTimeInMillis = System.currentTimeMillis() + time;
		intent.putExtra(TIME, atTimeInMillis);
		PendingIntent sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		am.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, sender);
		Toast.makeText(mContext, "123", Toast.LENGTH_SHORT).show();
	}
	
	public void stopTimer()
	{
		unRegisterReceiver();
		AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(NFC_TIMER_INTENT);
		//		intent.setClass(mContext, NfcTimerReceiver.class);
		//		intent.setData(Uri.parse(TIMER_DATA));
		PendingIntent sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_NO_CREATE);
		if (sender != null)
		{
			am.cancel(sender);
		}
	}
	
	private void registerReceiver()
	{
		if (mTimerServer == null)
		{
			mTimerServer = new NfcTimerReceiver();
			IntentFilter filter = new IntentFilter();
			filter.addAction(NFC_TIMER_INTENT);
			mContext.registerReceiver(mTimerServer, filter);
		}
	}
	
	private void unRegisterReceiver()
	{
		mContext.unregisterReceiver(mTimerServer);
		mTimerServer = null;
	}
	
	class NfcTimerReceiver extends BroadcastReceiver
	{
		@Override
		public void onReceive(Context context, Intent intent)
		{
			String action = intent.getAction();
			int id = intent.getIntExtra("id", -1);
			long alarmtime = intent.getLongExtra("alarm_time", -1);
			Log.i("lily", "received action = " + action + ", id = " + id + ", alarmtime = " + alarmtime);
			Toast.makeText(context, "received action = " + action + ", id = " + id, Toast.LENGTH_SHORT).show();
		}
	};
	
	//sps
	public void startSuperSowerSave(boolean on)
	{
		Intent i = new Intent("intent.action.super_power_save");
		i.putExtra("sps_action", !on ? "stop" : "start");
		mContext.sendBroadcast(i);
	}
	
	//kill
	private static final int RUNNING_ITEM_MAX_NUM = 100;
	private ActivityManager mAM;
	private static final String QUALC = "com.android.qualcomm";
	private static final String PCTOOLS = "com.bbk.PCTools";
	private static final String BBKDIALERINITSERVICE = "android.process.acore";
	private ArrayList < String > mWhiteProcessList;
	
	private class RunningItem
	{
		public ComponentName mComponent;
		
		public ApplicationInfo mAppInfo;
		
		public CharSequence mDisplayLabel;
		
		public RunningAppProcessInfo mProcessInfo;
		
		public RunningItem(String name)
		{
			mDisplayLabel = name;
		}
	}
	
	private void initWhiteList()
	{
		mWhiteProcessList = new ArrayList < String >(20);
		
		// �������Լ��ӽ���
		mWhiteProcessList.add("com.bbk.SuperPowerSave");
		// system process
		mWhiteProcessList.add("com.android.applicationmanager");
		mWhiteProcessList.add("com.android.settings");
		mWhiteProcessList.add("com.android.phone");
		mWhiteProcessList.add("com.android.systemui");
		mWhiteProcessList.add("com.google.process.gapps");
		mWhiteProcessList.add("android.process.acore");
		mWhiteProcessList.add("android.process.media");
		mWhiteProcessList.add("com.android.contacts");
		mWhiteProcessList.add("com.android.mms");
		
		//bbk process
		mWhiteProcessList.add("com.bbk.powerSavingAssistant");
		mWhiteProcessList.add("com.mediatek.engineermode");
		mWhiteProcessList.add("com.android.BBKSchpwronoff");
		mWhiteProcessList.add("com.bbk.theme");
		mWhiteProcessList.add("com.iqoo.securesecretary");
		mWhiteProcessList.add("com.bbk.weather.widget");
		mWhiteProcessList.add("com.bbk.healthy_eight_cup_water");
		mWhiteProcessList.add("com.android.BBKClock");
		mWhiteProcessList.add("com.bbk.calendar");//keep calendar reminders
		//do not kill wallpaper benin
		//		getWallPaperAndInputService();	
		//		mWhiteProcessList.addAll(wallPaperAndInputList);
		//do not kill wallpaper end
	}
	
	private void loadRunningApps(ArrayList < RunningItem > resultList)
	{
		if (resultList == null)
			return;
		
		RunningItem app = null;
		String label = null;
		final PackageManager pm = mContext.getPackageManager();
		ApplicationInfo aInfo = null;
		RunningTaskInfo tInfo = null;
		
		List < RunningTaskInfo > runningTaskList = mAM.getRunningTasks(RUNNING_ITEM_MAX_NUM);
		int runningTaskListSize = runningTaskList.size();
		
		for (int i = 0; i < runningTaskListSize; i++)
		{
			tInfo = runningTaskList.get(i);
			try
			{
				aInfo = pm.getApplicationInfo(tInfo.baseActivity.getPackageName(), 0);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			if (aInfo != null)
			{
				label = aInfo.packageName;
				app = new RunningItem(label);
				app.mAppInfo = aInfo;
				ComponentName component = new ComponentName(tInfo.baseActivity.getPackageName(), tInfo.baseActivity.getClassName());
				app.mComponent = component;
				resultList.add(app);
			}
		}
	}
	
	private void loadRunningServices(ArrayList < RunningItem > resultList)
	{
		if (resultList == null)
			return;
		
		String label = null;
		final PackageManager pm = mContext.getPackageManager();
		ApplicationInfo aInfo = null;
		
		RunningServiceInfo serviceInfo = null;
		RunningItem service = null;
		List < RunningServiceInfo > runningServiceList = mAM.getRunningServices(RUNNING_ITEM_MAX_NUM);
		int runningServiceListSize = runningServiceList.size();
		for (int i = 0; i < runningServiceListSize; i++)
		{
			serviceInfo = runningServiceList.get(i);
			if (!serviceInfo.started && serviceInfo.clientLabel == 0)
			{
				continue;
			}
			
			if ((serviceInfo.flags & ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS) != 0 && !serviceInfo.process.equals("com.android.bbkmusic"))
			{
				continue;
			}
			
			if (serviceInfo.clientLabel == 0)
			{
				try
				{
					aInfo = pm.getApplicationInfo(serviceInfo.service.getPackageName(), 0);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				if (aInfo != null)
				{
					label = aInfo.packageName;
					if (matchString(label, QUALC) || matchString(label, PCTOOLS) || matchString(label, BBKDIALERINITSERVICE))
					{
						continue;
					}
					if (serviceInfo.service.getClassName().contains("com.android.BBKClock.DateAppWidgetProvider") && serviceInfo.service.getClassName().contains("UpdateService"))
					{
						continue;
					}
					service = new RunningItem(label);
					service.mAppInfo = aInfo;
					service.mComponent = serviceInfo.service;
					resultList.add(service);
				}
			}
		}
	}
	
	private boolean matchString(String buffer, String text)
	{
		if (TextUtils.isEmpty(buffer) || TextUtils.isEmpty(text))
			return false;
		
		return buffer.equals(text);
	}
	
	public void killRunningApps()
	{
		ArrayList < RunningItem > totalRunningItemList = new ArrayList < RunningItem >(30);
		
		loadRunningApps(totalRunningItemList);
		loadRunningServices(totalRunningItemList);
		
		HashMap < String, RunningAppProcessInfo > runningProcessMap = new HashMap < String, RunningAppProcessInfo >();
		List < ActivityManager.RunningAppProcessInfo > runningProcessList = mAM.getRunningAppProcesses();
		RunningAppProcessInfo pInfo = null;
		int runningProcessListSize = runningProcessList.size();
		for (int i = 0; i < runningProcessListSize; i++)
		{
			pInfo = runningProcessList.get(i);
			if (pInfo.importance > RunningAppProcessInfo.IMPORTANCE_BACKGROUND) // ��Ҫ��̨���
				continue;
			if (runningProcessMap.containsKey(pInfo.processName)) // �ظ��Ĳ�Ҫ
				continue;
			if (mWhiteProcessList.contains(pInfo.processName)) // �����в�ɱ
				continue;
			runningProcessMap.put(pInfo.processName, pInfo);
		}
		
		HashSet < String > killList = new HashSet < String >(20);
		RunningItem item = null;
		final int triSize = totalRunningItemList.size();
		for (int i = 0; i < triSize; i++)
		{
			item = totalRunningItemList.get(i);
			pInfo = runningProcessMap.get(item.mAppInfo.processName); // ����������ڿ�ɱ�Ľ����
			if (pInfo != null)
			{
				item.mProcessInfo = pInfo;
				killList.add(item.mAppInfo.packageName);
			}
			else
			{
			}
		}
		
		try
		{
			final Iterator < String > elements = killList.iterator();
			while (elements.hasNext())
			{
				final String pkgName = elements.next();
				if (pkgName.equals("com.android.bbksoundrecorder"))
				{
					Intent i = new Intent("android.intent.action.CLOSE_RECENT_APP.com.android.bbksoundrecorder");
					mContext.sendBroadcast(i);
				}
				else if (pkgName.equals("android"))
				{
					Log.d(TAG, "skip stop process \"android\", it's so important!");
				}
				else
				{
					mAM.killBackgroundProcesses(pkgName);
				}
			}
			killList.clear();
			totalRunningItemList.clear();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	//phone
	public void callTel(String num)
	{
		if (isPhoneNumberValid(num) == true)
		{
			Uri uri = Uri.parse("tel:" + num);
			Intent intent = new Intent(Intent.ACTION_CALL, uri);
			mContext.startActivity(intent);
		}
	}
	
	//sms
	public void sendMessage(String addre, String mess)
	{
		SmsManager smsManager = SmsManager.getDefault();
		if (isPhoneNumberValid(addre) == true)
		{
			try
			{
				PendingIntent mPI = PendingIntent.getBroadcast(mContext, 0, new Intent(), 0);
				smsManager.sendTextMessage(addre, null, mess, mPI, null);
				//save message
				ContentValues values = new ContentValues();
				values.put("date", System.currentTimeMillis());//发送时间  
				values.put("read", 0);//阅读状态        
				values.put("type", 2);//1为收 2为发   
				values.put("address", addre);//送达号码 
				values.put("body", mess);//送达内容  
				mContext.getContentResolver().insert(Uri.parse("content://sms/sent"), values);//插入短信库    
			}
			catch (Exception e)
			{
				// TODO: handle exception  
			}
		}
	}
	
	public static boolean isPhoneNumberValid(String phoneNumber)
	{
		boolean isValid = false;
		String expression = "((^(13|15|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
		CharSequence inputStr = phoneNumber;
		Pattern pattern = Pattern.compile(expression);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches())
		{
			isValid = true;
		}
		return isValid;
	}
	
	public void getContactPick(Activity a)
	{
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType(ContactsContract.Contacts.CONTENT_TYPE);//vnd.android.cursor.dir/contact
		a.startActivityForResult(intent, PICK_CONTACT);
	}
	
	//锁屏
	public void lockNow()
	{
		Log.d(TAG, "--lockNow---");
		PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
		pm.goToSleep(SystemClock.uptimeMillis());
	}
	
	//Browser
	public void getAllBookmarks()
	{
		ContentResolver contentResolver = mContext.getContentResolver();
		Cursor cursor = null;
        String whereClause = Browser.BookmarkColumns.BOOKMARK;
        cursor = contentResolver.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, whereClause, null, null);
		if (cursor.moveToFirst())
		{
			int count = cursor.getCount();
			final CharSequence[] url = new CharSequence[count];
			final CharSequence[] title = new CharSequence[count];
			if (count > 0)
			{
				int i = 0;
				do
				{
					url[i] = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
					title[i] = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.TITLE));
					i++;
				}
				while (cursor.moveToNext());
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext).setTitle(R.string.hello_world).setItems(title, new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
					}
				});
				builder.show();
			}
		}
		cursor.close();
	}
	
	public void test()
	{
		//		startAlarm(0,0,"ok");
		//		startTimer(100);
		//		startSuperSowerSave(true);
		//		killRunningApps();
		//		callTel("10086");
		//		sendMessage("dddd13412792348", "3g");
		//		lockNow();
//		getAllBookmarks();
//		getContactPick(this);
//		intent = new Intent(this,AppShowActivity.class);
//		startActivityForResult(intent, OptApp.PICK_APP);
	}
}
